# Copyright (C) 2024 DFC Team (thelittlepony) & Nikus Team (openov)
# This File is licensed under GPLv3 License

import requests
import sys
import json
from types import SimpleNamespace
import platform

server_url = "https://notabug.org/Nikus-Team/nkpkg-repo/raw/master/*"

args = sys.argv
current = args[0]
#print(args)

current_arch = platform.processor()

try:
    command = args[1]
except:
    print(f"error: No command. Try {current} h")
    exit()

try:
    target = args[2]
except:
    target = None

# class BasePackage:
#     def __init__(self, name: str, description: str, author: str, version: str, arch: str):
#         self.name = name
#         self.description = description
#         self.author = author
#         self.version = version
#         self.arch = arch

class NKPKGInternal:
    def Search(name: str):
        payload = {"package": str}
        package_server = requests.get(f"{server_url}/api/search", json = payload)
        package = json.loads(package_server.content, object_hook=lambda d: SimpleNamespace(**d))

        package.name
        package.description
        package.author
        package.version
        package.arch

        packages = []

        if package.arch == current_arch:
            packages.append(Package)
        else:
            print(f"warn: {package.name} has {package.arch}, but your pc has {current_arch}. Skipping...")

        return packages
    
    def GetBinary(name: str, author: str, version: str, arch: str):
        payload = {"name": name, "author": author, "version": version, "arch": arch}
        try:
            binary_request = requests.get(f"{server_url}/api/get_binary")
        except:
            print("nkpkg: 52: can't get binary file")
            return {"error": True}

        try:
            binary_data = binary_request.content
            binary_file = open(f"{name}", "w")
            binary_file.write(binary_data)
            binary_file.close()
        except:
            print("nkpkg: 58-61: can't write file, or open it")
            return {"error": True}

        return {"error": False}

if command == "h":
    print(
        f"""
        Usage: {current} [action] [package]
        
        action:
            s - <package> - build package from source
            su <package> - build package from source on user repository (user repo can be changed at /etc/nkpkg/make.conf)
            b <package> - install binary package
            ss <package> - search package in the repos (urepo & repo)
            r <package> - remove package
            ra <package> - removes package and package data
            u - update all packages
            # us - sync repos
            fu - full upgrade of OS
        """
    )
    exit()
if command == "b":
    package = NKPKGInternal.Search(target)[0]
    binary_check_err = NKPKGInternal.GetBinary(package.name, package.author, package.version, package.arch)
    if binary_check_err["error"] == True:
        print(f"error: Can't install {target}. Check logs.")
    exit()
if command == "ss":
    package = NKPKGInternal.Search(target)[0]
    if len(package) > 0:
        print(f"""
        name: {package.name}
        description: {package.description}
        author: {package.author}
        version: {package.version}
        arch: {package.arch}
        """)
    else:
        print(f"error: No package found for {target}")
    exit()
else:
    print(f"error: Invalid command ({command}). Try {current} h")
    exit()
